package org.layui.servlet;

import org.layui.dao.UserDao;
import org.layui.dao.impl.UserDaoImpl;
import org.layui.utils.FileUploadUtil;
import org.layui.utils.JwtUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/api/user/upload")
@MultipartConfig
public class UserUploadHeadServlet extends BaseServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("attach") ;

        // 获取客户端发送过来的token
        String token = req.getHeader(JwtUtil.TOKEN_HEADER);
        String jwt = token.replace(JwtUtil.TOKEN_PREFIX, "");

        // 获取payload信息
        String username = JwtUtil.getPayload(jwt, "username", String.class);


        // 使用上传工具类来实现文件的上传
        FileUploadUtil fuu = new FileUploadUtil() ;
        // 获取图片上传的物理路径 File f = new File() ; f.create()
        String path = req.getServletContext().getRealPath("/file/head") ;

        // 设置允许上传文件的大小和类型-10MB
        fuu.setMaxSize(10*1024*1024);
        fuu.setAllowFileExt("jpg,png,jpeg");

        // 文件上传，并返回上传的文件名
        String filename = fuu.upload(part, path) ;

        // 查找之前的头像
        UserDao userDao = new UserDaoImpl();
        String image = userDao.selectUser(username).getImage();

        // 删除图片
        File f = new File(path+ File.separator+image) ;
        if(f.exists()) {
            f.delete();
        }
        // 修改图片
        userDao.updateHead(username,filename);

        print(resp, successJson(filename,200,"修改头像成功"));
    }
}
